package com.zbw;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;
import java.util.concurrent.Future;
@RunWith(SpringRunner.class)
@SpringBootTest()
public class AsyncTask {
    @Test
    public void xxx() throws InterruptedException {
        Future<String> taskA = execTaskA();
        Future<String> taskB = execTaskB();
        Future<String> taskC = execTaskC();
        //间隔一秒轮询 直到 A B C 全部完成
        if (taskA.isDone() && taskB.isDone() && taskC.isDone()) {
            System.out.println("任务结束，当前时间" + System.currentTimeMillis());
        }
        System.out.println("主线程");
    }
    @Async
    public Future<String> execTaskA() throws InterruptedException {
        System.out.println("TaskA开始");
        long star = new Date().getTime();
        Thread.sleep(1000);
        long end = new Date().getTime();
        System.out.println("TaskA结束，耗时毫秒数：" + (end - star));
        return new AsyncResult<>("TaskA结束");
    }

    @Async
    public Future<String> execTaskB() throws InterruptedException {
        System.out.println("TaskB开始");
        long star = new Date().getTime();
        Thread.sleep(3000);
        long end = new Date().getTime();
        System.out.println("TaskB结束，耗时毫秒数：" + (end - star));
        return new AsyncResult<>("TaskB结束");
    }

    @Async
    public Future<String> execTaskC() throws InterruptedException {
        System.out.println("TaskC开始");
        long star = new Date().getTime();
        Thread.sleep(2000);
        long end = new Date().getTime();
        System.out.println("TaskC结束，耗时毫秒数：" + (end - star));
        return new AsyncResult<>("TaskC结束");
    }
}

